package it.unibo.contact.EnvSystem;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import biz.source_code.base64Coder.Base64Coder;
import it.unibo.is.interfaces.IMessage;
import it.unibo.is.interfaces.platforms.IAcquireOneReply;

public class Process extends ProcessSupport 
{
	protected String key = "keyProcess";
	protected String value = "valueProcess";
	
	public Process() throws Exception {
		super();
	}
	
	@Override
	@Deprecated
	protected IAcquireOneReply hl_process_ask_putData_environment(String M) throws Exception {
		return super.hl_process_ask_putData_environment(M);
	}

	protected IAcquireOneReply hl_process_ask_putData_environment(String key, Object O) throws Exception 
	{
		return super.hl_process_ask_putData_environment(key+":"+toString(O));
	}
	
	@Override
	public void doJob() throws Exception 
	{	
		showMsg("putData: [" + key + ":" + value + "]");
		hl_process_ask_putData_environment(key+":"+value);
		
		sleep(10000);
		
		showMsg("getData: [" + key + "]");
		IAcquireOneReply reply = hl_process_demand_getData_environment(key);
		IMessage message = reply.acquireReply();
		showMsg("value: " + message.msgContent());      
	}
	
	
	/** Write the object to a Base64 string. */
	protected String toString( Object o ) 
	{
		ByteArrayOutputStream baos = null;

		if(o instanceof Serializable)
		{
			try
			{
				baos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream( baos );
				oos.writeObject( o );
				oos.close();
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}

			return new String( Base64Coder.encode( baos.toByteArray() ) );
		}
		
		return "";	//TODO Da rivedere
	}
	
	
	/** Read the object from Base64 string. */
	protected Object fromString( String s ) 
	{
		s = s.replace("'", "").trim();
		Object o = null;
		try
		{
			byte [] data = Base64Coder.decode( s );
			ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
			o  = ois.readObject();
			ois.close();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}

		return o;
	}

}
